//
//  RemindDetailedViewController.m
//  110
//
//  Created by 段报雪 on 16/4/11.
//  Copyright © 2016年 乔砥. All rights reserved.
//

#import "RemindDetailedViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "RemindModel.h"
#import "FMDB.h"
@interface RemindDetailedViewController ()<UITextFieldDelegate>

@property (nonatomic, strong)UIImageView *iconImageView;

@property (nonatomic, strong)UITextField *textField1;
@property (nonatomic, strong)UITextField *textField2;
@property (nonatomic, strong)UITextField *textField3;

@property (nonatomic, strong)UIDatePicker *datePicker;

@property (nonatomic, strong)UILabel *presentTime;

@property (nonatomic, strong)UILabel *timeLabel;

@property (nonatomic, strong)AVSpeechSynthesizer *synthesizer;

@property (nonatomic, strong)NSMutableArray *dateArray;

@property (nonatomic, assign)NSInteger y;
@property (nonatomic, assign)NSInteger m;
@property (nonatomic, assign)NSInteger d;
@property (nonatomic, assign)NSInteger h;
@property (nonatomic, assign)NSInteger min;
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, strong)NSDate *date;

@property (nonatomic, strong)FMDatabase *db;
@end

@implementation RemindDetailedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"服药提醒";
    _dateArray = [NSMutableArray array];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemAction:)];
    
    
    //  小图标
    _iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, KHEIGHT / 12  + 50 , 30, 30)];
    _iconImageView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:_iconImageView];
    
    _iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, KHEIGHT / 12 + 90, 30, 30)];
    _iconImageView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:_iconImageView];
    
    _iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, KHEIGHT / 12 + 130, 30, 30)];
    _iconImageView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:_iconImageView];
    
    _iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, KHEIGHT / 12 + 170, 30, 30)];
    _iconImageView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:_iconImageView];
    
    _iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30, KHEIGHT / 12 + 210, 30, 30)];
    _iconImageView.backgroundColor = [UIColor cyanColor];
    [self.view addSubview:_iconImageView];
    
    //  称呼文本框
    _textField1 = [[UITextField alloc] initWithFrame:CGRectMake(100, KHEIGHT / 12 + 50, KWIDTH - 50 - 100, 30)];
    _textField1.borderStyle = UITextBorderStyleRoundedRect;
    _textField1.placeholder = @"服药者称呼";
    _textField1.clearButtonMode = UITextFieldViewModeAlways;
    _textField1.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _textField1.returnKeyType = UIReturnKeyNext;
    _textField1.delegate = self;
    [self.view addSubview:_textField1];
    
    //  药品名称文本框
    _textField2 = [[UITextField alloc] initWithFrame:CGRectMake(100, KHEIGHT / 12 + 90, KWIDTH - 50 - 100, 30)];
    _textField2.borderStyle = UITextBorderStyleRoundedRect;
    _textField2.placeholder = @"药品名称";
    _textField2.clearButtonMode = UITextFieldViewModeAlways;
    _textField2.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _textField2.delegate = self;
    [self.view addSubview:_textField2];
    
    //  备注文本框
    _textField3 = [[UITextField alloc] initWithFrame:CGRectMake(100, KHEIGHT / 12 + 130, KWIDTH - 50 - 100, 30)];
    _textField3.borderStyle = UITextBorderStyleRoundedRect;
    _textField3.placeholder = @"输入备注";
    _textField3.clearButtonMode = UITextFieldViewModeAlways;
    _textField3.autocapitalizationType = UITextAutocapitalizationTypeNone;
    _textField3.delegate = self;
    [self.view addSubview:_textField3];

    //  创建显示时间、日历
    _date = [NSDate date];
    
    //  现在时间Label
    _presentTime = [[UILabel alloc] initWithFrame:CGRectMake(100, KHEIGHT / 12 + 170, KWIDTH - 50 - 100, 30)];
    _presentTime.backgroundColor = [UIColor grayColor];
    
    [self.view addSubview:_presentTime];
    
    //  设定提醒时间Label
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, KHEIGHT / 12 + 210, KWIDTH - 50 - 100, 30)];
    _timeLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:_timeLabel];
    
    //  时间选择器
    _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, KHEIGHT/ 3 + 110, KWIDTH, 130)];
    _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
    _datePicker.date = _date;
    [self.view addSubview:_datePicker];
    
    // 定时器 用来实时更新现在的时间
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[NSRunLoop currentRunLoop]addTimer:_timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop]run];
    });
    
    //  键盘回收
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    tap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tap];
    
}

#pragma mark ------键盘回收方法
- (void)tapAction:(UITapGestureRecognizer *)tap
{
    [self.view endEditing:YES];
}

#pragma mark ------ 点击return回收键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (void)timerAction:(NSTimer *)timer
{
    // 更新选择的时间
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //时区
    [dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    [dateFormatter setLocale:[NSLocale systemLocale]];
    NSString *dateTimeString = [dateFormatter stringFromDate:self.datePicker.date];
    self.timeLabel.text = dateTimeString;
    
    
    //  创建显示时间、日历 更新当前时间
    _date = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *dd = [calendar components:unitFlags fromDate:_date];
    _y= [dd year];
    _m = [dd month];
    _d = [dd day];
    _h = [dd hour];
    _min = [dd minute];

    self.presentTime.text = [NSString stringWithFormat:@"%ld-%02ld-%02ld %02ld:%02ld",_y,_m,_d,_h, _min];
}

- (void)rightBarButtonItemAction:(UIBarButtonItem *)sender
{
    if (_textField1.text.length == 0)
    {
        // 创建提示
        UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"用户名不能为空" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"重试" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        // 添加方法
        [Alert addAction:action];
        [self presentViewController:Alert animated:YES completion:nil];
        return;

    }
    if (_textField2.text.length == 0)
    {
        UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"药名不能为空" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"重试" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        // 添加方法
        [Alert addAction:action];
        [self presentViewController:Alert animated:YES completion:nil];
        return;
    }
    if (_textField3.text.length == 0)
    {
        UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入备注" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"重试" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        // 添加方法
        [Alert addAction:action];
        [self presentViewController:Alert animated:YES completion:nil];
        return;
    }
    NSString *year = [_timeLabel.text substringWithRange:NSMakeRange(5, 2)];
    NSString *year1 = [_presentTime.text substringWithRange:NSMakeRange(5, 2)];
    if ((NSInteger)year < (NSInteger)year1)
    {
        UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入正确月份" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        // 添加方法
        [Alert addAction:action];
        [self presentViewController:Alert animated:YES completion:nil];
        return;
    }
    NSString *year2 = [_timeLabel.text substringWithRange:NSMakeRange(8, 2)];
    NSString *year3 = [_presentTime.text substringWithRange:NSMakeRange(8, 2)];
    if ((NSInteger)year <= (NSInteger)year1 && (NSInteger)year2 < (NSInteger)year3)
    {
        UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请输入正确天数" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
        // 添加方法
        [Alert addAction:action];
        [self presentViewController:Alert animated:YES completion:nil];
        return;
    }
    NSString *year4 = [_timeLabel.text substringWithRange:NSMakeRange(11, 2)];
    NSString *year5 = [_presentTime.text substringWithRange:NSMakeRange(11, 2)];
    if ((NSInteger)year <= (NSInteger)year1 && (NSInteger)year2 <= (NSInteger)year3 && (NSInteger)year4 < (NSInteger)year5)
    {
        
        UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设置的时间不对哦" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        // 添加方法
        [Alert addAction:action];
        [self presentViewController:Alert animated:YES completion:nil];
        return;
    }
    NSString *year6 = [_timeLabel.text substringWithRange:NSMakeRange(14, 2)];
    NSString *year7 = [_presentTime.text substringWithRange:NSMakeRange(14, 2)];
    if ((NSInteger)year <= (NSInteger)year1 && (NSInteger)year2 <= (NSInteger)year3 && (NSInteger)year4 <= (NSInteger)year5 && (NSInteger)year6 <= (NSInteger)year7)
    {
        UIAlertController *Alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设置的分针不对哦" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        // 添加方法
        [Alert addAction:action];
        [self presentViewController:Alert animated:YES completion:nil];
        return;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
    // 点击确定 设置好时间之后添加本地提醒  用UILocalNotification来实现。
    [self scheduleLocalNotificationWithDate:self.datePicker.date];
    [self remindController:@"闹钟已经添加"];
    
    [self voiceAnnouncementsText:@"服药闹钟已经设定好"];
    RemindModel *model = [[RemindModel alloc]init];
    model.name = _textField1.text;
    model.date = _timeLabel.text;
    [_dateArray addObject:model];
 
    
}



- (void)scheduleLocalNotificationWithDate:(NSDate *)fireDate
{
    //0.创建推送
    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    //1.设置推送类型
    UIUserNotificationType type = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
    //2.设置setting
    UIUserNotificationSettings *setting  = [UIUserNotificationSettings settingsForTypes:type categories:nil];
    //3.主动授权
    [[UIApplication sharedApplication] registerUserNotificationSettings:setting];
    //4.设置推送时间
    [localNotification setFireDate:fireDate];
    //5.设置时区
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    NSDictionary * dic = [NSDictionary dictionaryWithObject:_timeLabel.text forKey:_textField1.text];
    localNotification.userInfo = dic;
    
    //6.推送内容
    [localNotification setAlertBody:@"亲！该吃药了!"];
    //7.推送声音
    [localNotification setSoundName:@"Thunder Song.m4r"];
      NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"date.db"];
    _db = [FMDatabase databaseWithPath:path];
    if (![_db open])
    {
        NSLog(@"无法打开闹钟数据库");
    }
    [_db executeUpdate:@"CREATE TABLE date(dateTime text , name text)"];
    
    [_db executeUpdate:@"INSERT INTO date(dateTime, name ) VALUES(?, ?)",_textField1.text,_timeLabel.text];

    
    
    
    //8.添加推送到UIApplication
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
}

//提示页面
- (void)remindController:(NSString *)remindText
{
    //提示页面（8.0出现）
    /**
     *  1.创建UIAlertController的对象
     2.创建UIAlertController的方法
     3.控制器添加action
     4.用presentViewController模态视图控制器
     */
    UIAlertController *alart = [UIAlertController alertControllerWithTitle:@"提示" message:remindText preferredStyle:UIAlertControllerStyleActionSheet];
    [self presentViewController:alart animated:YES completion:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [alart dismissViewControllerAnimated:YES completion:nil];
        });
    }];
}

//语音播报
- (void)voiceAnnouncementsText:(NSString *)text
{
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:text];
    [self.synthesizer speakUtterance:utterance];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
